import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'base_service.dart';

/// 实时视频管理服务类 - GetX服务
class VideoService extends GetxService {
  final BaseService _baseService = BaseService();

  /// 开始直播
  /// [serial] 设备ID
  /// [playType] 播放地址类型：WEBRTC、FLV、WS_FLV、RTMP、HLS、RTSP，默认RTMP
  Future<Map<String, dynamic>> startStream({
    required String serial,
    String? playType,
  }) async {
    try {
      String path = '/cms/stream/start?serial=$serial';
      // if (playType != null && playType.isNotEmpty) {
      //   path += '&playType=$playType';
      // }

      final response = await _baseService.get<Map<String, dynamic>>(path);

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '开始直播失败');
        }
      } else {
        throw Exception('开始直播响应数据为空');
      }
    } on DioException catch (e) {
      print('开始直播网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('开始直播错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 停止直播
  /// [serial] 设备ID
  /// [code] 通道ID（必填）
  /// [checkOutputs] 是否检查通道在线人数，默认false
  Future<Map<String, dynamic>> stopStream({
    required String serial,
    required String code,
    bool checkOutputs = false,
  }) async {
    try {
      final path =
          '/cms/stream/stop?serial=$serial&code=$code&check_outputs=$checkOutputs';

      final response = await _baseService.get<Map<String, dynamic>>(path);

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '停止直播失败');
        }
      } else {
        throw Exception('停止直播响应数据为空');
      }
    } on DioException catch (e) {
      print('停止直播网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('停止直播错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取对讲地址
  /// [serial] 设备ID
  /// [code] 通道ID
  Future<Map<String, dynamic>> getTalkUrl({
    required String serial,
    required String code,
  }) async {
    try {
      final path = '/cms/stream/getTalkUrl?serial=$serial&code=$code';

      final response = await _baseService.get<Map<String, dynamic>>(path);

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取对讲地址失败');
        }
      } else {
        throw Exception('获取对讲地址响应数据为空');
      }
    } on DioException catch (e) {
      print('获取对讲地址网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取对讲地址错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取HLS流地址
  Future<String?> getHLSUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'HLS');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取HLS流地址错误: $e');
      return null;
    }
  }

  /// 获取WEBRTC流地址
  Future<String?> getWebRTCUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'WEBRTC');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取WEBRTC流地址错误: $e');
      return null;
    }
  }

  /// 获取FLV流地址
  Future<String?> getFLVUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'FLV');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取FLV流地址错误: $e');
      return null;
    }
  }

  /// 获取WebSocket FLV流地址
  Future<String?> getWSFLVUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'WS_FLV');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取WS_FLV流地址错误: $e');
      return null;
    }
  }

  /// 获取RTMP流地址
  Future<String?> getRTMPUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'RTMP');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取RTMP流地址错误: $e');
      return null;
    }
  }

  /// 获取RTSP流地址
  Future<String?> getRTSPUrl(String serial) async {
    try {
      final response = await startStream(serial: serial, playType: 'RTSP');
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        // 直接使用SteamUrl
        return data['SteamUrl'] as String?;
      }
      return null;
    } catch (e) {
      print('获取RTSP流地址错误: $e');
      return null;
    }
  }

  /// 获取流的详细信息
  Future<Map<String, dynamic>?> getStreamInfo(String serial) async {
    try {
      final response = await startStream(serial: serial);
      return response['data'] as Map<String, dynamic>?;
    } catch (e) {
      print('获取流信息错误: $e');
      return null;
    }
  }

  /// 2.5.4 云台控制
  ///
  /// [serial] 设备编号 (必填)
  /// [code] 通道编号 (必填)
  /// [command] 控制指令 (必填): left, right, up, down, upleft, upright, downleft, downright, zoomin, zoomout, stop
  /// [speed] 速度(0~255)，默认129
  ///
  /// 返回控制结果
  Future<Map<String, dynamic>> controlPTZ({
    required String serial,
    required String code,
    required String command,
    int speed = 129,
  }) async {
    try {
      final queryParams = {
        'serial': serial,
        'code': code,
        'command': command,
        'speed': speed,
      };

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/control/ptz',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '云台控制失败');
        }
      } else {
        throw Exception('云台控制响应数据为空');
      }
    } on DioException catch (e) {
      print('云台控制网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('云台控制错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 2.9.5 云端抓图
  ///
  /// [serial] 设备编号 (必填)
  /// [channel] 通道序号，默认1
  /// [code] 通道编号，与channel二选一
  /// [timeout] 超时时间(秒)，默认15
  ///
  /// 返回Base64图片数据
  Future<Map<String, dynamic>> channelSnapshot({
    required String serial,
    int? channel,
    String? code,
    int timeout = 15,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'serial': serial,
        'timeout': timeout,
      };

      if (channel != null) {
        queryParams['channel'] = channel;
      }
      if (code != null && code.isNotEmpty) {
        queryParams['code'] = code;
      }

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/control/channelSnapshot',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '云端抓图失败');
        }
      } else {
        throw Exception('云端抓图响应数据为空');
      }
    } on DioException catch (e) {
      print('云端抓图网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('云端抓图错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }
}
